package com.buaa.airticketbookingsystem.Controller;

import com.buaa.airticketbookingsystem.Dao.UserDao;
import com.buaa.airticketbookingsystem.Entity.PurchaseRecord;
import com.buaa.airticketbookingsystem.Entity.Ticket;
import com.buaa.airticketbookingsystem.Entity.User;
import com.buaa.airticketbookingsystem.Service.PurchaseRecordService;
import com.buaa.airticketbookingsystem.Service.TicketService;
import com.buaa.airticketbookingsystem.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.relational.core.sql.In;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@CrossOrigin
@RestController
public class PurchaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private PurchaseRecordService purchaseRecordService;

    @Autowired
    private TicketService ticketService;

    @PostMapping("/pay")
    public Map<String, Object> BuyTickets(@RequestBody Map<String, Object> remap){
        double total = 0.0;
        String email = (String) remap.get("email");
        List<String> list = (ArrayList<String>) remap.get("List");
        System.out.println(list == null);
        System.out.println(list);
        List<PurchaseRecord> prList = new ArrayList<>();
        Map<String, Object> resMap = new HashMap<>();
        User u = userService.selectUserByEmail(email);
        for(String pr_id : list){
            PurchaseRecord pr = purchaseRecordService.getPurchaseRecordByNo(pr_id);
            total += pr.getPrice();
            prList.add(pr);
        }
        if(u.getMoney() < total){
            resMap.put("res", false);
            resMap.put("message", "余额不足，请充值");
            return resMap;
        } else {
            for (PurchaseRecord pr : prList) {
                String t_id = pr.getT_id();
                Ticket t = ticketService.getTicketById(t_id);
                try {
                    purchaseRecordService.payPurchaseRecord(pr.getWcnm(), pr.getEmail(), pr.getPrice());
                } catch (Exception e) {
                    e.printStackTrace();
                    resMap.put("res", false);
                    resMap.put("message", "购买失败，请重试或联系管理员解决");
                    return resMap;
                }
            }
        }
        resMap.put("res", true);
        resMap.put("message", "支付成功");
        return resMap;
    }
}
